#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <signal.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
#include <stdlib.h>

#define SERV_PORT 8888

void func(int arg)
{
	pid_t pid;
	int status;
	while((pid = waitpid(-1, &status, 0)) > 0){//() is crucial, or pid cannot be valued.
		if(WIFEXITED(status))
		printf("wait %dth child, pid: %d \n",WEXITSTATUS(status), pid);
	}
	return;
}

int main(int argc, char** argv)
{
	int serv_socket,  count = 0;
	char buf[BUFSIZ];
	struct sockaddr_in serv_addr;
	socklen_t socklen;

	pid_t pid;
	
	memset(&serv_addr, 0, sizeof(serv_addr));
	serv_addr.sin_family = AF_INET;
	serv_addr.sin_port = htons(SERV_PORT);
	serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);

	serv_socket = socket(AF_INET, SOCK_STREAM, 0);

	socklen = sizeof(serv_addr);
	bind(serv_socket, (struct sockaddr *)&serv_addr, socklen);

	listen(serv_socket, 5);

	int cli_socket;
	struct sockaddr_in cli_addr;
	memset(&cli_addr, 0, sizeof(cli_addr));
	socklen_t cli_socklen = sizeof(cli_addr);



	while(1)
	{
		cli_socket = accept(serv_socket, (struct sockaddr *)&cli_addr, &cli_socklen);
		count++;

		pid = fork();

		if(pid == 0)
		{
			close(serv_socket);
			printf("new client: ip: %s port: %d pid: %d\n", inet_ntoa(cli_addr.sin_addr), ntohs(cli_addr.sin_port), getpid());
			while(1){//necessary
				int ret = read(cli_socket, buf, sizeof(buf));
				if(ret == 0)//necessary
				{
					printf("a socket is closed.\n");
					return count;
				}				

				write(cli_socket, buf, ret);
			}
		}
		else
		{
			close(cli_socket);
			struct sigaction act,oldact;
			act.sa_handler = func;
			act.sa_flags = 0;
			sigemptyset(&act.sa_mask);
			sigaction(SIGCHLD, &act, &oldact);
		}	
	}

	return 0;
}
